<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.nickName"
        placeholder="请输入用户名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="用户编号" prop="id" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phoneNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status === '1' ? '启用':'禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="success" @click="handleDistributeRoles(row)">
            角色分配
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="账号" prop="username">
          <el-input v-model="temp.username" placeholder="请输入账号" :readonly="['update'].includes(dialogStatus)" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="用户名称" prop="nickName">
          <el-input v-model="temp.nickName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="手机号码" prop="phoneNum">
          <el-input v-model="temp.phoneNum" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="密码" prop="password">
          <el-input v-model="temp.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item v-if="['update','create'].includes(dialogStatus)" label="用户状态">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item.key" :label="item.text" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="['update'].includes(dialogStatus)" label="创建时间" prop="createTime">
          <el-date-picker v-model="temp.createTime" type="datetime" :readonly="['update'].includes(dialogStatus)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogPvVisible" title="角色分配">
      <div style="text-align: center">
        <el-transfer
          v-model="value.roles"
          style="text-align: left; display: inline-block"
          :render-content="renderFunc"
          :titles="['角色列表', '所属角色']"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}'
          }"
          :data="roles"
          @change="handleChange"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmData(value)">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, addUser, removeUser, modifyUser, listRole, listRoleByUserId, saveRoleByUserId } from '@/api/user/user-manager'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { validUsername, validPassword, validPhoneNum } from '@/utils/validate'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'UserManager',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    const generateData = _ => {
      const roles = []
      listRole({}).then(response => {
        const { data } = response
        const result = data || []
        result.forEach(item => {
          roles.push({
            key: item.id,
            label: item.roleName,
            disabled: item.id === 1
          })
        })
      })
      return roles
    }
    return {
      renderFunc(h, option) {
        return <span>{ option.key } - { option.label }</span>
      },
      value: {
        roles: [],
        userId: ''
      }, // 已选角色
      roles: generateData(), // 所有角色
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        nickName: ''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ key: '1', text: '启用' }, { key: '0', text: '禁用' }],
      showReviewer: false,
      temp: {
        id: '',
        username: '',
        nickName: '',
        phoneNum: '',
        password: '',
        status: '1'
      },
      dialogFormVisible: false,
      dialogFormVisible1: true,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {},
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys)
    },
    getList() {
      this.listLoading = true
      listUser(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        // Just to simulate the time of the request
        console.log('response', response)
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleDistributeRoles(row) {
      this.listLoading = true
      console.log('所有列表', this.roles)
      // 获取已选中角色列表
      listRoleByUserId({ id: row.id }).then(response => {
        const { data } = response
        const result = data || []
        const roles = []
        result.forEach(item => {
          roles.push(item.id)
        })
        this.value.roles = roles
        this.value = {
          roles: roles,
          userId: row.id
        }
        this.listLoading = false
      })
      this.dialogStatus = 'distribute'
      this.dialogPvVisible = true
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        username: '',
        nickName: '',
        phoneNum: '',
        password: '',
        status: '1'
      }
    },
    handleCreate() {
      this.rules = {
        username: [{ required: true, trigger: ['blur', 'change'], validator: validUsername }],
        phoneNum: [{ required: false, trigger: ['blur', 'change'], validator: validPhoneNum }],
        password: [{ required: true, trigger: ['blur', 'change'], validator: validPassword }]
      }
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.phoneNum === '') {
            delete this.temp.phoneNum
          }
          addUser(this.temp).then(response => {
            const { data } = response
            this.temp.id = data.id
            this.temp.createTime = data.createTime
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 3000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.rules = {}
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          modifyUser(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.total = this.total + 1
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    confirmData(value) {
      this.listLoading = true
      saveRoleByUserId({ 'roleIds': value.roles, 'userId': value.userId }).then(() => {
        // const index = this.list.findIndex(v => v.id === this.temp.id)
        // this.list.splice(index, 1, this.temp)
        this.listLoading = false
        this.$notify({
          title: '成功',
          message: '角色分配',
          type: 'success',
          duration: 2000
        })
        this.dialogPvVisible = false
      })
    },
    handleDelete(row, index) {
      removeUser({ id: row.id }).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
